package service

import (
	"blog-back-end/common/utils"
	user2 "blog-back-end/models/user"
	"blog-back-end/token"
	"errors"
	"github.com/asaskevich/govalidator"
)

func Login(username string, password string) (string, error) {
	affected := utils.DB.Where("username=? and password=?", username, password).First(&user2.User{}).RowsAffected
	//logger.Info("affected", affected)
	if affected == 0 {
		return "", errors.New("账号或秘密错误")
	}
	//生成token
	genToken, err := token.GenToken(username)
	if err != nil {
		return "", err
	}

	return genToken, nil

}

func Register(userRegisterData *user2.RegisterDTO) error {
	affected := utils.DB.Where("username=?", userRegisterData.Username).First(&user2.User{}).RowsAffected
	if affected == 1 {
		return errors.New("用户名已存在，请重新输入用户名")
	}

	if userRegisterData.Password == userRegisterData.Repassword {

		_, err1 := govalidator.ValidateStruct(userRegisterData)
		if err1 != nil {
			//context.JSON(200, gin.H{
			// TODO
			//	"message": err1.Error(),
			//	"code":    500,
			//})
			return err1
		}
		//TODO
		err := utils.DB.Create(&user2.User{
			Username: userRegisterData.Username,
			Password: userRegisterData.Password,
			Email:    userRegisterData.Email,
			Phone:    userRegisterData.Phone,
			Address:  userRegisterData.Address,
			Gender:   userRegisterData.Gender,
		}).Error

		if err != nil {
			return err
		}
		//TODO
		//fmt.Println("创建用户成功")
		return nil
	} else {
		return errors.New("两次输入密码不一致")
	}
}
